//
//  RACRadioButton.swift
//  I.S.A.P WT
//
//  Created by Илья Проскурнев on 10.08.2020.
//  Copyright © 2020 Илья Проскурнев. All rights reserved.
//

import Foundation
import UIKit

@objc protocol RACRadioButtonDelegate {
    @objc func racSelectButton(selectedButton: UIButton?)
}

class RACRadioButton : NSObject
{
    var str = ""
    fileprivate var buttonsArray = [UIButton]()
    weak var delegate : RACRadioButtonDelegate? = nil
    var shouldLetDeSelect = false

    init(buttons: UIButton...) {
        super.init()
        for aButton in buttons {
            aButton.addTarget(self, action: #selector(SASRadioButton.pressed(_:)), for: UIControl.Event.touchUpInside)
        }
        self.buttonsArray = buttons
    }

    func setButtonsArray(_ aButtonsArray: [UIButton]) {
        for aButton in aButtonsArray {
            aButton.addTarget(self, action: #selector(SASRadioButton.pressed(_:)), for: UIControl.Event.touchUpInside)
        }
        buttonsArray = aButtonsArray
    }

    @objc func pressed(_ sender: UIButton) {
        var currentSelectedButton: UIButton? = nil
        if(sender.isSelected) {
            if shouldLetDeSelect {
                sender.isSelected = false
                currentSelectedButton = nil
            }
        } else {
            for aButton in buttonsArray {
                aButton.isSelected = false
            }
            sender.isSelected = true
            currentSelectedButton = sender
        }
        delegate?.racSelectButton(selectedButton: currentSelectedButton)
    }

    func selectedButton() -> UIButton? {
        guard let index = buttonsArray.firstIndex(where: { button in button.isSelected }) else { return nil }
        return buttonsArray[index]
    }
    
}
